package com.roamer.audition.web.security.service;

import com.auth0.jwt.JWT;
import com.auth0.jwt.algorithms.Algorithm;
import org.springframework.security.core.userdetails.User;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.security.core.userdetails.UserDetailsService;
import org.springframework.security.core.userdetails.UsernameNotFoundException;
import org.springframework.security.crypto.password.PasswordEncoder;
import org.springframework.stereotype.Service;

import java.util.Date;
import java.util.Objects;

/**
 * 管理平台用户接口
 *
 * @author roamer
 * @version v1.0
 * @date 2020/3/9 16:33
 */
@Service
public class SystemPlatformUserUserServiceImpl implements UserDetailsService, JwtUserService {

    private final PasswordEncoder passwordEncoder;

    public SystemPlatformUserUserServiceImpl(PasswordEncoder passwordEncoder) {
        this.passwordEncoder = passwordEncoder;
    }

    @Override
    public UserDetails getUserLoginInfo(String username) {
        String salt = "123456ef";
        /*
         * todo 从数据库或者缓存中取出jwt token生成时用的salt
         * salt = redisTemplate.opsForValue().get("token:"+username);
         */
        UserDetails user = loadUserByUsername(username);
        // 将salt放到password字段返回
        return User.builder().username(user.getUsername()).password(salt).authorities(user.getAuthorities()).build();
    }

    @Override
    public String generateToken(UserDetails user) {
        // 实时生成加密的salt
        String salt = "123456ef";//BCrypt.gensalt();
        /*
         * todo 将salt保存到数据库或者缓存中
         * redisTemplate.opsForValue().set("token:"+username, salt, 3600, TimeUnit.SECONDS);
         */
        Algorithm algorithm = Algorithm.HMAC256(salt);
        //设置1小时后过期
        return JWT.create()
                .withSubject(user.getUsername())
                //设置1小时后过期
                .withExpiresAt(new Date(System.currentTimeMillis() + 3600 * 1000))
                .withIssuedAt(new Date())
                .withIssuer("roamer-auth")
                .sign(algorithm);
    }

    @Override
    public UserDetails loadUserByUsername(String username) throws UsernameNotFoundException {
        if (!Objects.equals("Jack", username)) {
            return null;
        }
        return User.builder().username("Jack").password(passwordEncoder.encode("jack-password")).roles("USER").build();
    }

    public void createUser(String username, String password) {
        String encryptPwd = passwordEncoder.encode(password);
        /**
         * @todo 保存用户名和加密后密码到数据库
         */
    }

    /**
     * 删除用户
     *
     * @param username
     */
    public void clearToken(String username) {
        /**
         * @todo 清除数据库或者缓存中登录salt
         */
    }
}
